﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using ESupervision.Models;
using ESupervision.ViewModels;
using ESupervision.Services;
using ESupervision.Logging;


namespace ESupervision.Controllers
{
    [Authorize(Roles="Authorised")]
    public class AllocatingController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        private readonly INotificationService notificationService;
        private readonly ILogger logger;

        public AllocatingController(INotificationService notificationService, ILogger logger)
        {
            this.notificationService = notificationService;
            this.logger = logger;
        }

        //
        // GET: /Allocating/
        public async Task<ActionResult> Index()
        {
            var identityusers = db.Students.Include(s => s.AuthorisedStaff).Include(s => s.SecondMarker).Include(s => s.Supervisor);
            return View(await identityusers.ToListAsync());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Allocate(string[] selectedStudents)
        {
            List<Student> students = new List<Student>();
            if (selectedStudents != null)
            {
                foreach (var studentId in selectedStudents)
                {
                    var student = db.Students.Find(studentId);
                    if (student != null)
                    {
                        students.Add(student);
                    }
                }

                
                ViewBag.Supervisor = new SelectList(db.Teachers, "Id", "FullName");
                ViewBag.SecondMarker = new SelectList(db.Teachers, "Id", "FullName");

                return View(students);
            }
            logger.Warning("The selected students list is empty.");
            ViewBag.Supervisor = new SelectList(db.Teachers, "Id", "FullName");
            ViewBag.SecondMarker = new SelectList(db.Teachers, "Id", "FullName");
            return View(students);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> AllocateCompleted(string[] studentIds, string Supervisor, string SecondMarker)
        {
          
            if (studentIds != null)
            {
                List<Teacher> oldTeachers = new List<Teacher>();
                List<Student> students = new List<Student>();
                foreach (var studentId in studentIds)
                {
                    var student = db.Students.Find(studentId);

                    if (student != null)
                    {
                        if (student.SupervisorUserId != Supervisor)
                        {
                            if (!oldTeachers.Contains(student.Supervisor))
                                oldTeachers.Add(student.Supervisor);
                            student.SupervisorUserId = Supervisor;
                        }

                        if (student.SecondMarkerUserId != SecondMarker)
                        {
                            if (!oldTeachers.Contains(student.SecondMarker))
                                oldTeachers.Add(student.SecondMarker);
                            student.SecondMarkerUserId = SecondMarker;
                        }
                        students.Add(student);
                    }
                    else
                    {
                        logger.Error("Cannot find student with id = " + studentId);
                    }
                }

                await db.SaveChangesAsync();

                List<Teacher> newTeachers = new List<Teacher>();
                newTeachers.Add(db.Teachers.Find(Supervisor));
                newTeachers.Add(db.Teachers.Find(SecondMarker));
                // Send notification email to related members.
                
                await notificationService.SendAllocatedNotificationToStudents(students);
                await notificationService.SendAllocatedNotificationToTeachers(newTeachers);
                if (oldTeachers.Count > 0)
                {
                    await notificationService.SendDeallocatedNotificationToTeachers(oldTeachers);
                }

                ViewBag.Message = "Allocate successful. The notification emails have already sent out to the related members";
                var identityusers = db.Students.Include(s => s.AuthorisedStaff).Include(s => s.SecondMarker).Include(s => s.Supervisor);
                return View("Index", await identityusers.ToListAsync());
            }
          return RedirectToAction("Index");
        }



	}
}